package com.showcai.util;

import com.showcai.tools.ToolsBase;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.nio.charset.Charset;

/**
 * Created by Baggio on 2018-9-3.
 */
public class DesTools extends ToolsBase {

    /**
     * 加密
     * @param data
     * @param sKey
     * @return
     */
    private static byte[] encrypt(byte[] data, String sKey) {
        try {
            byte[] key = sKey.getBytes();
            // 初始化向量
            IvParameterSpec iv = new IvParameterSpec(key);
            DESKeySpec desKey = new DESKeySpec(key);
            // 创建一个密匙工厂，然后用它把DESKeySpec转换成securekey
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey securekey = keyFactory.generateSecret(desKey);
            // Cipher对象实际完成加密操作
            Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
            // 用密匙初始化Cipher对象
            cipher.init(Cipher.ENCRYPT_MODE, securekey, iv);
            // 现在，获取数据并加密
            // 正式执行加密操作
            return cipher.doFinal(data);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解密
     * @param src
     * @param sKey
     * @return
     * @throws Exception
     */
    private static byte[] decrypt(byte[] src, String sKey) throws Exception {
        byte[] key = sKey.getBytes();
        // 初始化向量
        IvParameterSpec iv = new IvParameterSpec(key);
        // 创建一个DESKeySpec对象
        DESKeySpec desKey = new DESKeySpec(key);
        // 创建一个密匙工厂
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        // 将DESKeySpec对象转换成SecretKey对象
        SecretKey securekey = keyFactory.generateSecret(desKey);
        // Cipher对象实际完成解密操作
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        // 用密匙初始化Cipher对象
        cipher.init(Cipher.DECRYPT_MODE, securekey, iv);
        // 真正开始解密操作
        return cipher.doFinal(src);
    }

    /**
     * 将二进制转换成16进制
     *
     * @param buf
     * @return
     */
    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * 将16进制转换为二进制
     *
     * @param hexStr
     * @return
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) return null;
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }


    /**
     * 加密
     * @param srcStr
     * @param charset
     * @param sKey
     * @return
     */
    public static String encrypt(String srcStr, Charset charset, String sKey) {
        byte[] src = srcStr.getBytes(charset);
        byte[] buf = DesTools.encrypt(src, sKey);
        return DesTools.parseByte2HexStr(buf);
    }

    /**
     * 解密
     *
     * @param hexStr
     * @param sKey
     * @return
     * @throws Exception
     */
    public static String decrypt(String hexStr, Charset charset, String sKey) throws Exception {
        byte[] src = DesTools.parseHexStr2Byte(hexStr);
        byte[] buf = DesTools.decrypt(src, sKey);
        return new String(buf, charset);
    }

    public static void main(String[] args) {
       // String ss=   DesTools.encrypt("schedule/modifySchedule?userId=1&devicId=123&title=标题&context=内容&loop=2&remindPoint=1-3-5,0730",Charset.forName("UTF-8"),"abcdefrt");
        //    String ss=   DesTools.encrypt("certificate/userGain/404202/1538461777034003",Charset.forName("UTF-8"),"abcdefrt");
        //   String ss=   DesTools.encrypt("productEntity/getProductEntityList/4",Charset.forName("UTF-8"),"abcdefrt");
  //     String ss=   DesTools.encrypt("dictation/mediaClassifyList?tid=9",Charset.forName("UTF-8"),"abcdefrt");
       String ss=   DesTools.encrypt("dictation/index",Charset.forName("UTF-8"),"abcdefrt");
        //   String ss=   DesTools.encrypt("certificatePack/getCertificate/br4ngcna",Charset.forName("UTF-8"),"abcdefrt");
      //  String ss=   DesTools.encrypt("schedule/get/scheduleList/357409039059672",Charset.forName("UTF-8"),"abcdefrt");
        //  String ss=   DesTools.encrypt("schedule/modifySchedule/357409039059672/1",Charset.forName("UTF-8"),"abcdefrt");
         //  String ss=   DesTools.encrypt("schedule/modifySchedule?357409039059672/1?&title=标题&context=内容&loop=2&remindPoint=1-3-5,0730",Charset.forName("UTF-8"),"abcdefrt");
             //   "&title=标题&context=内容&loop=2&remindPoint=1-3-5,0730"
        System.out.println(ss);


        try {
            String ss1=   DesTools.decrypt(ss,Charset.forName("UTF-8"),"abcdefrt");

            System.out.println(ss1);
        } catch (Exception e) {
            e.printStackTrace();
        }

  /*      try {
            System.out.println(DesTools.decrypt("A73A0C01DCD462C1CB1F180E65A41C13CAA1EE56392AF1F83E540D43B081F4899D0DB996952E9E107072D521183155F2",Charset.forName("UTF-8"),"abcdefrt"));
            System.out.println(DesTools.decrypt("A73A0C01DCD462C1533F7E7A364B69853DA34077AE68A0EBA4B1776E2D6808D23A929D65C65B0BBEE453E70FDC666611",Charset.forName("UTF-8"),"abcdefrt"));
            System.out.println(DesTools.decrypt("A73A0C01DCD462C1533F7E7A364B69852B43D8F62A59C577169D9F33321E03932E6537F694F27CA37ADF6D7DCD3B6374",Charset.forName("UTF-8"),"abcdefrt"));
            System.out.println(DesTools.decrypt("A73A0C01DCD462C1533F7E7A364B69852B43D8F62A59C577169D9F33321E03932E6537F694F27CA37ADF6D7DCD3B6374",Charset.forName("UTF-8"),"abcdefrt"));
        } catch (Exception e) {
            e.printStackTrace();
        }*/
    }
}
